//
//  ViewController.swift
//  swiftTableView
//
//  Created by 梁佳佳 on 2016/10/20.
//  Copyright © 2016年 梁佳佳. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var frameModel:FrameModel = FrameModel(array: [])
    //MARK: - 视图加载
    override func viewDidLoad() {
        super.viewDidLoad()
        //创建数据
        self.createDataSource()
        //创建UI
        self.createUI()
    }
    //MARK: - 创建UI
    func createUI() -> Void {
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.editButton)
    }
    //MARK: - 初始化数据
    func createDataSource() -> Void {
        let dic1:NSDictionary = ["imagename" : "1", "name" : "A", "description" : "try to learn swift 3.0"]
        let dic2:NSDictionary = ["imagename" : "2", "name" : "B", "description" : "maybe want to change the job"]
        let dic3:NSDictionary = ["imagename" : "1", "name" : "C", "description" : "the teacher"]
        let dic4:NSDictionary = ["imagename" : "2", "name" : "D", "description" : "maybe like E"]
        let dic5:NSDictionary = ["imagename" : "1", "name" : "E", "description" : "love B"]
        
        let array:NSArray = [[dic1, dic2, dic3], [dic4, dic5], [dic1, dic4], [dic2, dic3, dic1, dic5], [dic2], [dic1, dic2, dic3, dic4, dic5]]
        //i从0~array.count
        for i in 0 ..< array.count {
            let tempArr:NSArray = array[i] as! NSArray
            self.frameModel = FrameModel(array: tempArr)
            self.frameModel.isOpen = false
            self.dataSource.add(self.frameModel)
        }
    }
    //MARK: - tableView的代理方法
    //行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let frameModel:FrameModel = self.dataSource[section] as! FrameModel
        if frameModel.isOpen {
            return frameModel.array.count
        }
        else
        {
            return 0
        }
    }
    //组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataSource.count
    }
    //创建cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier:String = "cellIdentifier"
        var cell:MyTableViewCell? = tableView.dequeueReusableCell(withIdentifier: identifier) as! MyTableViewCell?
        if (cell == nil) {
            cell = MyTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: identifier)
        }
        cell?.selectionStyle = .none//选择样式
        cell?.accessoryType = .checkmark//cell右侧显示的图标
        let frameModel:FrameModel = self.dataSource[indexPath.section] as! FrameModel
        if frameModel.isOpen {
            let tableModel:TableModel = frameModel.array[indexPath.row] as! TableModel
            cell?.createDataWithModel(tableModel: tableModel)
        }
        return cell!
    }
    //设置组头的高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 60
    }
    //设置组尾的高度
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1
    }
    //设置行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let frameModel:FrameModel = self.dataSource[indexPath.section] as! FrameModel
        if frameModel.isOpen {
            return 60
        }
        else
        {
            return frameModel.closeFrame
        }
    }
    //点击单元格
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print("点击了第\(indexPath.section + 1)组，第\(indexPath.row + 1)个单元格")
        let alert:UIAlertController = UIAlertController(title: "点击提示", message: "您点击了第\(indexPath.section + 1)组，第\(indexPath.row + 1)个单元格", preferredStyle: UIAlertControllerStyle.alert)
        let action:UIAlertAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.default, handler: { (action) in
            tableView.reloadData()
            print("default")
        })
        let cancel:UIAlertAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (cancel) in
            print("cancel")
            tableView.reloadData()
        })
        alert.addAction(action)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
    //设置索引
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        let arr:[String] = NSArray(array: self.searchArray) as! [String]
        return arr
    }
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        var tpIndex:NSInteger = 0
        let arr:[String] = NSArray(array: self.searchArray) as! [String]
        //遍历索引
        for character in arr {
            if character == title {
                return tpIndex
            }
            else
            {
                tpIndex += 1 //swift 3.0去掉了++，--
            }
        }
        return 0
    }
    //MARK: - 编辑
    //是否可以编辑
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    //编辑的类型
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        let frameModel:FrameModel = self.dataSource[indexPath.section] as! FrameModel
        if indexPath.row == frameModel.array.count - 1{
            return .insert//插入
        }
        return .delete//删除
    }
    //移动单元格
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    //删除的字样
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    //创建组头视图
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let button:UIButton = UIButton(type: .custom)
        button.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 60)
        button.backgroundColor = UIColor.white
        button.tag = section
        button.setTitle(NSString.init(format: "%d", section + 1) as String, for: .normal)
        button.setTitleColor(UIColor.blue, for: .normal)
        button.addTarget(self, action: #selector(headButtonMethod(_:)), for: UIControlEvents.touchUpInside)
        return button
    }
    //编辑cell
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let frameModel:FrameModel = self.dataSource[indexPath.section] as! FrameModel
        if editingStyle == .delete {
            //数组中删除
            frameModel.array.removeObject(at: indexPath.row)
            //表格删除对应行
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
        else if editingStyle == .insert
        {
            //数组中添加
            let dic:NSDictionary = ["name" : "temp", "imagename" : "1", "description" : "temp"]
            let tableModel:TableModel = TableModel.init(dic: dic)
            frameModel.array.insert(tableModel, at: indexPath.row)
            //表格中添加
            tableView.insertRows(at: [indexPath], with: .middle)
        }
        tableView.reloadData()
    }
    //移动单元格
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let frameModel:FrameModel = self.dataSource[sourceIndexPath.section] as! FrameModel
        if sourceIndexPath != destinationIndexPath {
            if destinationIndexPath.section > sourceIndexPath.section {
                //获取移动行对应的值
                let value:TableModel = frameModel.array[sourceIndexPath.row] as! TableModel
                //删除移动行的值
                frameModel.array.removeObject(at: sourceIndexPath.row)
                let desFrameModel:FrameModel = self.dataSource[destinationIndexPath.section] as! FrameModel
                if desFrameModel.isOpen == false {
                    desFrameModel.array.add(value)
                }
                else
                {
                    desFrameModel.array.insert(value, at: destinationIndexPath.row)
                }
                desFrameModel.isOpen = true
                tableView.reloadData()
            }
            else
            {
                //获取移动行对应的值
                let value:TableModel = frameModel.array[sourceIndexPath.row] as! TableModel
                //删除移动行的值
                frameModel.array.removeObject(at: sourceIndexPath.row)
                //如果移动的区域大于先有的行数，直接在最后添加移动的值
                if destinationIndexPath.row > sourceIndexPath.row {
                    frameModel.array.add(value)
                }
                else
                {
                    //没有超过先有的行数
                    frameModel.array.insert(value, at: destinationIndexPath.row)
                }
                tableView.reloadData()
            }
        }
    }
    //组头按钮的回调方法
    func headButtonMethod(_ sender: UIButton) -> Void {
        let frameModel:FrameModel = self.dataSource[sender.tag] as! FrameModel
        frameModel.isOpen = !frameModel.isOpen
        let indexSet:NSIndexSet = NSIndexSet(index: sender.tag)
        self.tableView.reloadSections(indexSet as IndexSet, with: UITableViewRowAnimation.fade)
    }
    //编辑按钮回调方法
    func editButtonMethod(_ sender:UIButton) -> Void {
        if sender.isSelected {
            sender.setTitle("取消", for: .normal)
            self.tableView.setEditing(true, animated: true)
        }
        else
        {
            sender.setTitle("编辑", for: .normal)
            self.tableView.setEditing(false, animated: true)
        }
        sender.isSelected = !sender.isSelected
    }
    //MARK: - 懒加载
    //懒加载tableView
    lazy var tableView: UITableView = {
        var tempTableView = UITableView(frame: CGRect(x: 0, y: self.editButton.frame.maxY + 10, width: self.view.frame.size.width, height: self.view.frame.size.height - self.editButton.frame.maxY - 30), style: UITableViewStyle.grouped)
        tempTableView.delegate = self
        tempTableView.dataSource = self
        tempTableView.bounces = false
        return tempTableView
    }()
    //懒加载数组
    lazy var dataSource: NSMutableArray = {
        var tempArray = NSMutableArray()
        return tempArray
    }()
    //懒加载按钮
    lazy var editButton: UIButton = {
        var button:UIButton = UIButton(type: UIButtonType.custom)
        button.frame = CGRect(x: 10, y: 20, width: self.view.frame.size.width - 20, height: 40)
        button.setTitle("编辑", for: .normal)
        button.backgroundColor = UIColor.red
        button.layer.cornerRadius = 5
        button.layer.masksToBounds = true
        button.isSelected = true
        button.setTitleColor(UIColor.white, for: .normal)
        button.addTarget(self, action: #selector(editButtonMethod(_:)), for: .touchUpInside)
        return button
    }()
    //懒加载索引数组
    lazy var searchArray: NSMutableArray = {
        var tempArray:NSMutableArray = NSMutableArray()
        for i in 0..<self.dataSource.count {
            let string: NSString = NSString.init(format: "%d", i + 1)
            tempArray.add(string)
        }
        return tempArray
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

